#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/23 11:21
# @Author  : 李中华
# @Email   : 1260429766@qq.com
# @File    : logger.py
import logging
from logging import handlers
from ProgramPath import programPath
import os
import time

logPath = os.path.join(programPath, 'report', 'log')


class Log:

    def __init__(self):
        logFile = time.strftime("%Y%m%d", time.localtime(time.time()))
        createLogPath()
        self.logFilePath = os.path.join(logPath, logFile + '.log')

    def setMsg(self, level, msg):
        '''logger是提供我们记录日志的方法；
        handler是让我们选择日志的输出地方，如：控制台，文件，邮件发送等，一个logger添加多个handler；
        filter是给用户提供更加细粒度的控制日志的输出内容；
        formater用户格式化输出日志的信息。'''

        format = logging.Formatter(fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s : %(message)s')
        logger = logging.getLogger()

        fh = handlers.TimedRotatingFileHandler(filename=self.logFilePath, when='D', interval=1, backupCount=7,
                                               encoding='utf-8')
        ch = logging.StreamHandler()

        fh.setFormatter(format)
        ch.setFormatter(format)

        logger.addHandler(fh)
        logger.addHandler(ch)

        logger.setLevel(logging.INFO)

        if level == 'debug':
            logger.debug(msg)
        if level == 'info':
            logger.info(msg)
        if level == 'warning':
            logger.warning(msg)
        if level == 'error':
            logger.error(msg)

        logger.removeHandler(fh)
        logger.removeHandler(ch)

    def debug(self, msg):
        self.setMsg('debug', msg)

    def info(self, msg):
        self.setMsg('info', msg)

    def warning(self, msg):
        self.setMsg('warning', msg)

    def error(self, msg):
        self.setMsg('error', msg)


def createLogPath():
    if not os.path.exists(logPath):
        os.makedirs(logPath)
        Log().info('{}日志目录不存在，现创建成功'.format(logPath))
    else:
        pass


if __name__ == '__main__':
    log = Log()
    # log.debug("debug")
    log.info("info")
    log.warning("warning")
    # log.error("error")
